package com.camartsApp.Util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class AliyunOssUtil {

    @Value("${aliyun.access_key_id}")
    private String accessKeyId;

    @Value("${aliyun.access_key_secret}")
    private String accessKeySecret;

    @Value("${aliyun.bucket}")
    private String bucketName;

    @Value("${aliyun.endpoint}")
    private String endpoint;

    /**
     * 上传文件到阿里云 OSS，并返回完整访问 URL
     */
    public String upload(MultipartFile file) {
        try {
            // 构造唯一文件名：photo/20250614_UUID_原始文件名
            String originalName = file.getOriginalFilename();
            String fileName = "photo/" + UUID.randomUUID() + "_" + originalName;

            // 获取文件输入流
            InputStream inputStream = file.getInputStream();

            // 创建 OSS 客户端
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 上传
            ossClient.putObject(bucketName, fileName, inputStream);

            // 关闭 OSS 客户端
            ossClient.shutdown();

            // 返回公网访问地址
            return "https://" + bucketName + "." + endpoint + "/" + fileName;

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("上传失败：" + e.getMessage());
        }
    }
}